package logic

import (
	"context"
	"errors"
	"github.com/eeppee_admin/clouddisk/service/internal/svc"
	"github.com/eeppee_admin/clouddisk/service/internal/types"
	"github.com/eeppee_admin/clouddisk/service/model"
	"github.com/eeppee_admin/clouddisk/service/helper"
	"github.com/zeromicro/go-zero/core/logx"
)

type ShareSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewShareSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShareSaveLogic {
	return &ShareSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ShareSaveLogic) ShareSave(req *types.ShareSaveRequest, userIdentity string) (resp *types.ShareSaveResponse, err error) {
	sp := new(model.StorePool)
	has, err := l.svcCtx.Engine.
		Where("identity = ?", req.StoreIdentity).
		Get(sp)
	if err != nil {
		return nil, err
	}

	if !has {
		return nil, errors.New("资源不存在")
	}

	us := &model.UserStore{
		Identity: helper.UUID(),
		UserIdentity: userIdentity,
		ParentId: req.ParentId,
		StoreIdentity: req.StoreIdentity,
		Ext: sp.Ext,
		Name: sp.Name,
	}

	_, err = l.svcCtx.Engine.Insert(us)
	resp = new(types.ShareSaveResponse)
	resp.Identity = us.Identity
	return
}
